/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-11-24，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.ui.activity;

import java.util.Map;

import com.chinamobile.ln.ictenterprises.R;
import com.chinamobile.ln.ictenterprises.common.Config;
import com.chinamobile.ln.ictenterprises.common.Constants;
import com.chinamobile.ln.ictenterprises.common.GlobalSetting;
import com.chinamobile.ln.ictenterprises.common.MainApplication;
import com.chinamobile.ln.ictenterprises.http.HttpAsyncTask;
import com.chinamobile.ln.ictenterprises.http.HttpSend;
import com.chinamobile.ln.ictenterprises.model.Step;
import com.chinamobile.ln.ictenterprises.model.request.Logout;
import com.chinamobile.ln.ictenterprises.ui.adapter.MenuAdapter;
import com.chinamobile.ln.ictenterprises.utils.ActivityStackManager;
import com.chinamobile.ln.ictenterprises.utils.JsonUtil;
import com.chinamobile.ln.ictenterprises.widget.SlidingMenu;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("HandlerLeak")
@SuppressWarnings("deprecation")
public class MainActivity extends ActivityGroup implements OnClickListener,
    OnItemClickListener, SlidingMenu.OnOpenedListener,
    SlidingMenu.OnOpenListener, SlidingMenu.OnCloseListener,
    SlidingMenu.OnClosedListener
{
    private MainApplication app;
    private SlidingMenu menu;// 菜单
    private View menuView;// 菜单视图
    private ListView menuList;// 菜单列表
    private LinearLayout pageContainer;// 内容布局
    private Window pageView = null;
    private MenuAdapter menuAdapter;
    private TextView tv_quit, head_name;
    private SharedPreferences sharedPref;
    private Context context;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        context = this;
        setContentView(R.layout.main);
        ActivityStackManager.getManager().addActivity(this);
        app = (MainApplication) getApplication();
        sharedPref = getSharedPreferences(Constants.LOGIN_SHAREDPREF,
            Context.MODE_PRIVATE);
        pageContainer = (LinearLayout) findViewById(R.id.main_content);
        menuView = getLayoutInflater().inflate(R.layout.menu_list, null);
        menuList = (ListView) menuView.findViewById(android.R.id.list);
        tv_quit = (TextView) menuView.findViewById(R.id.tv_quit);
        head_name = (TextView) menuView.findViewById(R.id.head_name_txt);
        head_name.setText(sharedPref.getString(Constants.ALIAS, null));
        tv_quit.setOnClickListener(this);
        menuAdapter = new MenuAdapter(0, this);
        menuList.setAdapter(menuAdapter);
        menuList.setOnItemClickListener(this);
        initMenu();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
    }

    private void initMenu()
    {
        // 配置菜单
        menu = new SlidingMenu(this);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        menu.setShadowWidthRes(R.dimen.shadow_width);// 设置menu边缘阴影宽度s
        // menu.setShadowDrawable(R.drawable.base_slidingmenu_shadow);//
        // 设置menu边缘阴影
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);// 设置menu宽度
        menu.setBehindScrollScale(0.0f);
        // menu.setFadeDegree(0.35f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);// 菜单绑定到Activity
        menu.setMenu(menuView);
        menu.setOnOpenListener(this);
        menu.setOnOpenedListener(this);
        menu.setOnCloseListener(this);
        menu.setOnClosedListener(this);
        app.setMenu(menu);
        switchActivity(Constants.MENU_SEND);
    }

    private void switchActivity(int type)
    {
        app.setCurrentMenu(type);
        switch (type)
        {
        case Constants.MENU_SEND:
            loadActivity(SendMsgActivity.class, Constants.MENU_SEND_ACTIVITY_ID);

            break;
        case Constants.MENU_HISTORY:
            loadActivity(HistoryActivity.class,
                Constants.MENU_HISTORY_ACTIVITY_ID);
            break;
        }
    }

    /**
     * 跳转到相关Activity
     */
    private void loadActivity(Class<?> clazz, String activityId)
    {
        if (!isCurrentActivity(activityId))
        {
            pageContainer.removeAllViews();
            Intent intent = new Intent(this, clazz);
            pageView = getLocalActivityManager().startActivity(activityId,
                intent);
            pageContainer.addView(pageView.getDecorView(),
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        }
    }

    /**
     * 判断是否为当前Activity
     * 
     * @param activityId
     * @return
     */
    private boolean isCurrentActivity(String activityId)
    {

        String currentId = getLocalActivityManager().getCurrentId();
        if (currentId != null && currentId.equalsIgnoreCase(activityId))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public void onClosed()
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void onClose()
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void onOpen()
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void onOpened()
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int position,
        long arg3)
    {
        TextView tvMenuId = (TextView) view.findViewById(R.id.tv_menu_id);
        int menu_id = Integer.parseInt(tvMenuId.getText().toString());
        app.getMenu().showContent();
        switchActivity(menu_id);// 根据点击位置跳转
        menuAdapter.changeState(position);// 改变adapter里点击的背景颜色改变
    }

    @Override
    public void onClick(View v)
    {
        new AlertDialog.Builder(context).setTitle(R.string.logout_title)
            .setMessage(R.string.logout_msg)
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {

                }
            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    logout();
                }
            }).show();
    }

    /** 登出 **/
    private void logout()
    {
        Logout logout = new Logout(GlobalSetting.LOGOUT);
        String params = JsonUtil.objectToJson(logout);
        dialog = ProgressDialog.show(this, "温馨提示", "正在退出登录...");
        dialog.setCanceledOnTouchOutside(false);
        Step step = new Step();
        step.setUrl(Config.USER_LOGIN);
        step.setStreamString(params);
        step.setEncoding("UTF-8");
        step.setRequestType(HttpSend.JSON_REQUEST);
        HttpAsyncTask httpAsyncTask = new HttpAsyncTask(step,
            HttpAsyncTask.CACHE_TYPE_ACTION, sharedPref.getString(
                Constants.COOKIES, ""), GlobalSetting.USER_LOGOUT);
        httpAsyncTask.setUIHandler(logoutHandler);
        new Thread(httpAsyncTask).start();
    }

    private Handler logoutHandler = new Handler() {
        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            if (msg.obj != null)
            {
                // Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                // int reultCode = (Integer) httpMap
                // .get(GlobalSetting.STUATUS_CODE);
                sharedPref.edit().putBoolean(Constants.LOGIN_AUTOLOGIN, false)
                    .commit();
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
            dialog.dismiss();
        };
    };

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

}
